<script setup lang="ts">
import "../../utils/xterm.css";
import "../../utils/xterm.js";
// import '../../../node_modules/@xterm/xterm/lib/xterm.js';
// import '../../../node_modules/@xterm/xterm/css/xterm.css'
import { useRoute, useRouter } from "vue-router";
import { message } from "@/utils/message";
import { onMounted, onUnmounted } from "vue";
const route = useRoute();
const router = useRouter();
onMounted(() => {
  checkProtocol();
});
onUnmounted(() => {
  stopHeartbeat();
});
let heartbeatTimerId;
const startHeartbeat = data => {
  heartbeatTimerId = setInterval(() => {
    data.send("");
  }, 10000);
};
const stopHeartbeat = () => {
  clearInterval(heartbeatTimerId);
};

//判断协议
const checkProtocol = () => {
  if (
    window.location.protocol === "https:" &&
    route.query.serevr_addr.split(":")[0] == "ws"
  ) {
    console.log("当前页面使用的是 HTTPS 协议。");
    message("当前是https环境，请为容器控制台配置ssl证书", { type: "error" });
    router.back();
  } else {
    console.log("当前页面使用的是 HTTP 协议。");
    function resizeTerminal(term) {
      const container = document.getElementById("container-terminal");
      if (!container) {
        console.error("Container element not found.");
        return;
      }
      // 现在使用更精确的测量值，这些值应该基于你的终端设置
      const style = window.getComputedStyle(container);
      const charWidth =
        parseInt(style.getPropertyValue("--xterm-char-width"), 10) || 10;
      const charHeight =
        parseInt(style.getPropertyValue("--xterm-char-height"), 10) || 20;

      const width = container.offsetWidth;
      const height = container.offsetHeight;

      const cols = Math.floor(width / charWidth);
      console.log(cols);
      const rows = Math.floor(height / charHeight);

      term.resize(cols, rows);
      console.log(term);
    }

    function getQueryVar(variable) {
      const query = window.location.search.substring(1);
      const vars = query.split("&");
      for (let i = 0; i < vars.length; i++) {
        const pair = vars[i].split("=");
        if (pair[0] === variable) {
          return pair[1];
        }
      }

      return false;
    }
    let token = route.query.token;
    if (!token) {
      throw new Error("token not found");
    }

    let serevr_addr = route.query.serevr_addr;
    if (!serevr_addr) {
      throw new Error("serevr_addr not found");
    }

    let command = getQueryVar("cmd");
    if (!command) {
      command = "/bin/bash";
    }

    let websocket = new WebSocket(
      serevr_addr + "/console/" + "exec/" + token + "," + window.btoa(command)
    );
    websocket.onerror = function (evt) {
      console.log(evt);
      message("网络波动", { type: "error" });
      router.back();
    };
    websocket.onopen = function () {
      let term = new Terminal({
        cols: 300,
        rows: 30,
        screenKeys: true,
        useStyle: true,
        cursorBlink: true
      });
      console.log("打开终端", term);
      startHeartbeat(websocket);

      term.on("data", function (data) {
        websocket.send(data);
      });

      term.on("title", function (title) {
        document.title = title;
      });

      term.open(document.getElementById("container-terminal"), true);

      resizeTerminal(term);

      window.addEventListener("resize", () => {
        resizeTerminal(term);
      });

      websocket.onmessage = function (evt) {
        term.write(evt.data);
        console.log("发送信息", evt);
      };

      websocket.onclose = function () {
        term.write("Session terminated");
        term.destroy();
      };

      websocket.onerror = function (evt) {
        // if (typeof console.log == "function") {
        //   console.log(evt)
        // }
        if (evt) {
          message("网络波动", { type: "error" });
          router.back();
        }
      };
    };
  }
};
</script>

<template>
  <div id="container-terminal" />
</template>

<style lang="scss" scoped>
body {
  padding: 0;
  margin: 5px;
  background-color: #000;
  height: 100%;
}

#container-terminal {
  width: 100%;
  height: 85%;
  margin: 0;
  padding: 0;
}
</style>
